//
//  HTInviteCopilotController.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/27.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTInviteCopilotController.h"

/// iOS 9前的框架
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
/// iOS 9的新框架
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
#import <ContactsUI/ContactsUI.h>
#endif
@interface HTInviteCopilotController ()<ABPeoplePickerNavigationControllerDelegate,CNContactPickerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;

@end

@implementation HTInviteCopilotController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"邀请副驾";
    self.phoneTextField.delegate = self;
    [self.phoneTextField addTarget:self action:@selector(phoneTextValueChanged:) forControlEvents:UIControlEventEditingChanged];
    self.phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
   
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneTextField) {
        if (textField.text.length >= 11 && string.length > 0) {
            return NO;
        }else{
            return YES;
        }
    }
    return NO;
}

//手机文本框文本改变
- (void)phoneTextValueChanged:(UITextField *)sender {
    
}

//点击空白处键盘退出
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.phoneTextField resignFirstResponder];
  
}

- (IBAction)didClickBindBtn:(UIButton *)sender {
    if (self.phoneTextField.text == nil || self.phoneTextField.text.length <= 0) {
        [HTShowUtil showMessage:@"请输入手机号码"];
        return;
    }
    [self netLoadData];
}
- (IBAction)didClickChoseContact:(UIButton *)sender {
    [self JudgeAddressBookPower];
}

#pragma mark ---- 调用系统通讯录
- (void)JudgeAddressBookPower { ///获取通讯录权限，调用系统通讯录
    [self CheckAddressBookAuthorization:^(bool isAuthorized , bool isUp_ios_9) { if (isAuthorized) {
        [self callAddressBook:isUp_ios_9];
        
    }else {
        NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
        
    }
    }];
    
}
- (void)callAddressBook:(BOOL)isUp_ios_9 {
    if (isUp_ios_9) {
    CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
    contactPicker.delegate = self;
    contactPicker.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
    [self presentViewController:contactPicker animated:YES completion:nil];
}else {
    ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
    peoplePicker.peoplePickerDelegate = self;
    [self presentViewController:peoplePicker animated:YES completion:nil]; } }

- (void)CheckAddressBookAuthorization:(void (^)(bool isAuthorized , bool isUp_ios_9))block {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        CNContactStore * contactStore = [[CNContactStore alloc]init];
        if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
            [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * __nullable error) {
                if (error) {
                    NSLog(@"Error: %@", error);
                    
                } else if (!granted){
                    block(NO,YES);
                    
                } else {
                    block(YES,YES);
                    
                }
                
            }]; } else if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized){
                block(YES,YES);
                
            } else {
                NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
                
            }
    }else {
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL); ABAuthorizationStatus authStatus = ABAddressBookGetAuthorizationStatus();
        if (authStatus == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                dispatch_async(dispatch_get_main_queue(), ^{ if (error) {
                    NSLog(@"Error: %@", (__bridge NSError *)error);
                    
                } else if (!granted) {
                    block(NO,NO);
                    
                } else {
                    block(YES,NO);
                    
                }
                    
                });
                
            });
            
        }else if (authStatus == kABAuthorizationStatusAuthorized) {
            block(YES,NO);
            
        }else{
            NSLog(@"请到设置>隐私>通讯录打开本应用的权限设置");
            
        }
        
    }
    
}
#pragma mark -- CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    CNPhoneNumber *phoneNumber = (CNPhoneNumber *)contactProperty.value;
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *text1 = [NSString stringWithFormat:@"%@%@",contactProperty.contact.familyName,contactProperty.contact.givenName];
        /// 电话
        NSString *text2 = phoneNumber.stringValue;
        self.phoneTextField.text = text2;
        NSLog(@"联系人：%@, 电话：%@",text1,text2);
    }];
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
    CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef,index);
    CFStringRef anFullName = ABRecordCopyCompositeName(person);
    
    [self dismissViewControllerAnimated:YES completion:^{
        /// 联系人
        NSString *text1 = [NSString stringWithFormat:@"%@",anFullName];
        /// 电话
        NSString *text2 = (__bridge NSString*)value;
        self.phoneTextField.text = text2;
        NSLog(@"联系人：%@, 电话：%@",text1,text2);
    }];
}
#pragma  mark --- 网络请求
- (void)netLoadData{
    [self startHud];
    [HTHttpRequestManager requestBindCopilotsWithPhone:self.phoneTextField.text success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"绑定：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"绑定失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [self alertMessage:responseObject[@"message"]];
            return;
        }
        [self alertMessage:responseObject[@"message"]];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"绑定失败"];
    }];
}
- (void)alertMessage:(NSString *)message{
    [UIAlertController alertStyleShowInController:self title:@"" message:message alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
    } completion:nil];
}
@end
